﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ADOX;
using System.Data.OleDb; 
using System.IO;

namespace LogCat.Utility
{
    class DBUtility
    {

        public static string dbpath = "";//数据库路径

        static string Tag = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName;

        //获取数据库连接
        static OleDbConnection _conn = null;
        static OleDbConnection conn
        { 
            get{
                if (_conn == null)
                {
                    _conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source="+dbpath);
                    _conn.Open();
                }
                return _conn;
            }
        }
        
        //创建数据库
        public static bool CreateDB(string path) 
        {
            dbpath = path;

            Log.i(Tag,"create db ：path=" +path);

            ADOX.Catalog catalog = new Catalog();

            try
            {
                catalog.Create("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Jet OLEDB:Engine Type=5");
            }
            catch(Exception e)
            {
                Log.w(Tag,e.Message);
            }
            
            bool exists = File.Exists(path);

            if(!exists){
                Log.e(Tag,"create db failed !");
            }

            return exists; 
        }


        //创建表
        public static void CreateTable(string name,string[] feild) {
            string sql = "create table " + name + " (id AUTOINCREMENT(0,1),";
            for (int i = 0; i < feild.Length;i++ )
            {
                sql += feild[i] + " Memo";
                if((i+1) != feild.Length){
                    sql += ",";
                }
            }
            sql +=  ");";

            Log.i(Tag,sql);
            OleDbCommand cmd = new OleDbCommand(sql,conn);
            cmd.ExecuteNonQuery();
        }

        //插入数据
        public static int Insert(string table,Dictionary<string,string> data) 
        {
            string key = "", value = "";
            foreach(string k in data.Keys){
                key     += k+",";
                value   += "'"+data[k] + "',";
            }
            key = key.TrimEnd(',');
            value = value.TrimEnd(',');
            string sql = "insert into " +table+"("+key+") values ("+value+");";
            Log.i(Tag,sql);
            OleDbCommand cmd = new OleDbCommand(sql, conn);
            return cmd.ExecuteNonQuery();
        }

        //查询
        public static OleDbDataReader Select(string sql)
        {
            OleDbCommand cmd = new OleDbCommand(sql,conn);
            return cmd.ExecuteReader();
        }
    }
}
